package com.itheima.mobileController;

import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.constant.MessageConstant;
import com.itheima.constant.RedisMessageConstant;
import com.itheima.entity.Result;
import com.itheima.pojo.Order;
import com.itheima.pojo.Setmeal;
import com.itheima.service.OrderService;
import com.itheima.utils.SMSUtils;
import com.itheima.utils.ValidateCodeUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import redis.clients.jedis.JedisPool;

import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * <h3>health94_pareant</h3>
 * <p></p>
 *
 * @author : hhw
 * @date : 2020-03-29 11:06
 **/
@RestController
@RequestMapping("order")
public class OrderController {
    @Autowired
    private JedisPool jedisPool;


    @Reference
    private OrderService orderService;

    @RequestMapping("orderadd")
    public Result OrderAdd(@RequestBody Map map) {
        try {
            if (map.get("telephone")==null || map.get("validateCode")==null) {
                return new Result(false, MessageConstant.TELEPHONE_VALIDATECODE_NOTNULL);
            }
            //提交过来之后,先校验验证码是否正确
            String telephone = (String)(map.get("telephone"));
            String validateCode = (String)(map.get("validateCode"));
            String redisKey = telephone + RedisMessageConstant.SENDTYPE_ORDER;
            String redisCode = jedisPool.getResource().get(redisKey);
            if (redisCode == null || !redisCode.equals(validateCode)) {
                return new Result(false, MessageConstant.VALIDATECODE_ERROR);
            }
           //手机和验证码都不为空, 验证码验证通过,向数据库添加预约订单
            Order order = orderService.add(map);
            //向手机发送预约成功消息
            Integer noticeCode = ValidateCodeUtils.generateValidateCode(4);
            SMSUtils.sendShortMessage(SMSUtils.ORDER_NOTICE, telephone, String.valueOf(noticeCode));
            return new Result(true, MessageConstant.ADD_ORDER_SUCCESS, order);
        } catch (Exception e) {
            return new Result(false, MessageConstant.ADD_ORDER_FAIL);
        }
    }

    @RequestMapping("orderInfo")
    public Result orderInfo(@RequestParam("id") Integer id) {
        try {
            Map orderInfo = orderService.orderInfo(id);
            return new Result(true, MessageConstant.QUERY_ORDER_SUCCESS, orderInfo);
        } catch (Exception e) {
            return new Result(false, MessageConstant.QUERY_ORDER_FAIL);
        }


    }

}
